const async = require('async');
module.exports = {
    open: false,
    description: '搜索评论',
    handler(req, res, next) {
        let doc = req.query;
        let filter = doc.filter || {};
        let search = filter.search || "";
        var page = doc.page;
        let skip = 0;
        let limit = 10;
        if (page) {
            if (page.size) {
                limit = page.size;
                if (page.index > 1) {
                    skip = (page.index - 1) * page.size;
                }
            }
        }
        async.auto([
                callback => req.mongo.collection("comment").aggregate([
                    {
                        $lookup: {
                            from: "card",
                            localField: "cardID",
                            foreignField: "_id",
                            as: "cardTitle"
                        }
                    },
                    {$unwind: "$cardTitle"},
                    {$match: {$or: [{"cardTitle.nickname": {$regex: search}}, {"cardTitle.title": {$regex: search}}]}},
                    {$sort: {"cardTitle.title": 1}},
                ]).toArray(callback)
            ],
            (err, results) => {
                if (err) return res.err.mongoError(err);
                const comment = results[0] || [];
                if (!page) {
                    return res.reply(comment);
                }
                let count = comment.length;
                page.size = page.size || 10;
                page.index = page.index || 1;
                page.count = count;
                page.pageCount = Math.ceil(page.count / page.size);
                if (count <= 0) return res.reply(page);
                page.hasPrevious = page.index > 1;
                page.hasNext = page.index < page.pageCount;
                page.index = page.pageCount < page.index ? page.pageCount : page.index;
                page.items = comment.slice(skip, skip + limit);
                return res.reply({code: 0, message: "查询成功", data: page});
            }
        )
    }
};

